package com.proton.carepatchtemp.utils.Log;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.application.VCare;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;


/**
 * Created by MoonlightSW on 2016/11/15.
 */

public class L {
    public static final String CACHE_DIR_NAME = "CarePatchLog";
    public static final String TAG = "CarePatchTemp";
    public static boolean isDebugModel = true;// 是否输出日志
    public static boolean isSaveDebugInfo = true;// 是否保存调试日志
    public static boolean isSaveCrashInfo = true;// 是否保存报错日志
    private static DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);

    private L() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    private static String generateTag(StackTraceElement caller, String customTagPrefix) {
        String tag = "%s.%s(Line:%d)"; // 占位符
        String callerClazzName = caller.getClassName(); // 获取到类名
        callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);
        tag = String.format(tag, callerClazzName, caller.getMethodName(), caller.getLineNumber()); // 替换
        tag = TextUtils.isEmpty(customTagPrefix) ? tag : customTagPrefix + ":" + tag;

        return tag;
    }

    private static StackTraceElement getCallerStackTraceElement() {
        return Thread.currentThread().getStackTrace()[4];
    }


    public static void v(final String tag, final String msg) {
        if (isDebugModel) {
            StackTraceElement caller = getCallerStackTraceElement();
            Log.v(generateTag(caller, tag), msg);
        }
    }

    public static void d(final String tag, final String msg) {
        if (isDebugModel) {
            LogUtils.d(tag, msg);
        }
    }

    public static void i(final String tag, final String msg) {
        if (isDebugModel) {
            LogUtils.i(tag, msg);
        }
    }

    public static void w(final String tag, final String msg) {
        if (isDebugModel) {
            LogUtils.w(tag, msg);
        }
    }


    /**
     * 调试日志，便于开发跟踪。
     */
    public static void e(final String TAG, final String msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.e(tag, msg);
        }

        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }

            }.start();
        }
    }

    /**
     * try catch 时使用，上线产品可上传反馈。
     */
    public static void e(final String TAG, final Throwable tr) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isSaveCrashInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " [CRASH] --> "
                            + getStackTraceString(tr) + "\n");
                }
            }.start();
        }
    }


    public static void v(final String msg) {
        if (isDebugModel) {
            LogUtils.v(msg);
        }
    }

    public static void d(final String msg) {
        if (isDebugModel) {
            LogUtils.d(msg);
        }
    }


    public static void i(final String msg) {
        if (isDebugModel) {
            LogUtils.i(msg);
        }
    }

    public static void w(final String msg) {
        if (isDebugModel) {
            LogUtils.w(msg);
        }
    }

    /**
     * 调试日志，便于开发跟踪。
     */
    public static void e(final String msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            Log.e(tag, msg);
        }

        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    /****************************************************************
     * 调试方法L.d                         *
     * Array, Map, Set and List are supported         *
     * START                            *
     ****************************************************************/

    public static void d(final Object msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.d(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }

            }.start();
        }
    }

    public static void d(final List msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.d(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }

            }.start();
        }
    }

    public static void d(final Map msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.d(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }

            }.start();
        }
    }

    public static void d(final Set msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.d(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }

            }.start();
        }
    }

    public static void d(final String[] msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
//            LogUtils.d(tag,  msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void d(final String TAG, final Object msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.d(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }

            }.start();
        }
    }

    public static void d(final String TAG, final List msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.d(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }

            }.start();
        }
    }

    public static void d(final String TAG, final Map msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.d(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }

            }.start();
        }
    }

    public static void d(final String TAG, final Set msg) {

        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.d(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void d(final String TAG, final String[] msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);
        if (isDebugModel) {
//            LogUtils.d(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }

            }.start();
        }
    }
    /****************************************************************
     *                          调试方法L.d                         *
     *               Array, Map, Set and List are supported         *
     *                              END                             *
     ****************************************************************/

    /****************************************************************
     * 调试方法L.e                         *
     * Array, Map, Set and List are supported         *
     * START                            *
     ****************************************************************/

    public static void e(final Object msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.e(tag, msg);
        }

        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void e(final List msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.e(tag, msg);
        }

        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void e(final Map msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.e(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void e(final Set msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.e(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void e(final String[] msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            Log.e(tag, msg.toString());
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void e(final String TAG, final Object msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.e(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void e(final String TAG, final List msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.e(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void e(final String TAG, final Map msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.e(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void e(final String TAG, final Set msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
            LogUtils.e(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }

    public static void e(final String TAG, final String[] msg) {
        StackTraceElement caller = getCallerStackTraceElement();
        String tag = generateTag(caller, TAG);

        if (isDebugModel) {
//            LogUtils.e(tag, msg);
        }
        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    write(time() + tag + " --> " + msg + "\n");
                }
            }.start();
        }
    }


    /****************************************************************
     *                          调试方法L.e                         *
     *               Array, Map, Set and List are supported         *
     *                             END                            *
     ****************************************************************/

    /**
     * try catch 时使用，上线产品可上传反馈。
     */
    public static void e(final Throwable tr) {

        if (isDebugModel) {
            LogUtils.e(tr);
        }
        if (isSaveCrashInfo) {
            new Thread() {
                public void run() {
                    write(time() + TAG + " [CRASH] --> "
                            + getStackTraceString(tr) + "\n");
                }
            }.start();
        }
    }


    /**
     * 获取捕捉到的异常的字符串
     */
    public static String getStackTraceString(Throwable tr) {
        if (tr == null) {
            return "";
        }

        Throwable t = tr;
        while (t != null) {
            if (t instanceof UnknownHostException) {
                return "";
            }
            t = t.getCause();
        }

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        tr.printStackTrace(pw);
        return sw.toString();
    }

    /**
     * 标识每条日志产生的时间
     */
    private static String time() {
        return "["
                + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(
                System.currentTimeMillis())) + "] ";
    }

    /**
     * 以年月日作为日志文件名称
     */
    private static String date() {
        return new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss").format(new Date(System
                .currentTimeMillis()));
    }

    /**
     * 保存到日志文件
     */
    public static synchronized void write(String content) {
        try {
            FileWriter writer = new FileWriter(getEDirectory("Log"), true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取日志文件路径
     */
    public static String getFile() {
        File sdDir = null;


        if (Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED))
            sdDir = Environment.getExternalStorageDirectory();

        File cacheDir = new File(sdDir + File.separator + CACHE_DIR_NAME);
        if (!cacheDir.exists())
            cacheDir.mkdir();

        File filePath = new File(cacheDir + File.separator + date() + ".txt");

        return filePath.toString();
    }

    public static String getEDirectory(String folderName) {
        if (Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState())) {
//            LogUtils.e(Environment.getExternalStoragePublicDirectory(folderName).getAbsolutePath());
//            return Environment.getExternalStoragePublicDirectory(folderName).getAbsolutePath();
//            return Environment.getExternalStorageDirectory()getExternalFilesDir;
//            LogUtils.e( VCare.get().getExternalFilesDir(folderName).getAbsolutePath());
            return VCare.get().getExternalFilesDir(folderName).getAbsolutePath();
        } else {
//            LogUtils.e("external error");
//            return Environment.getExternalStorageDirectory()+"/vcare"+File.separator+folderName;
            return VCare.get().getFilesDir().getAbsolutePath() + File.separator + folderName;

        }
    }

    /**
     * 奔溃信息收集
     */
    public static void crashLog(final String msg) {
        if (isDebugModel) {
            Log.e(TAG, msg);
        }

        if (isSaveDebugInfo) {
            new Thread() {
                public void run() {
                    try {

                        File cacheDir = new File(getEDirectory(CACHE_DIR_NAME));
                        if (!cacheDir.exists())
                            cacheDir.mkdir();

                        File filePath = new File(cacheDir + File.separator + date() + "_Crash" + ".txt");

                        FileWriter writer = new FileWriter(filePath.toString(), true);
                        writer.write(msg);
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    write(time() + TAG + " --> " + msg + "\n");
                }
            }.start();
        }
    }
}
